import { logManager } from '@/utils/log';
import { ref } from 'vue';

const errMsgMap = {
  userLocation: '使用"地图"功能, 需要获取"位置信息"权限',
  addPhoneContact: '使用"存入手机通讯录"功能, 需要获取"添加到通讯录"权限',
  userInfo: '',
  address: '',
  invoiceTitle: '',
  invoice: '',
  werun: '',
  record: '',
  writePhotosAlbum: '',
  camera: '使用"核验签到"功能, 需要获取"相机"权限',
  bluetooth: '',
  addPhoneCalendar: '',
};

export type ScopeType = keyof typeof errMsgMap;

export function useAuthSetting() {
  const scopeTypeRef = ref();

  /** 检查授权 */
  function hasSettingStatus(): Promise<boolean> {
    const settingKey = `scope.${scopeTypeRef.value}` as keyof AuthSetting;
    return new Promise((resolve, reject) => {
      uni.getSetting({
        success: ({ authSetting }) => resolve(authSetting[settingKey]),
        fail: (err) => {
          console.error('getSetting fail ===>', err);
          logManager.error(err)
          reject(false);
        },
      });
    });
  }

  /** 授权错误处理 */
  async function authErrorCallbak(
    scopeType: ScopeType,
    error: { errno?: number; errMsg?: string },
    showCancel: boolean = true
  ) {
    const { errno, errMsg } = error;

    if (errno === 103 && (errMsg?.includes('fail auth deny') || errMsg?.includes('auth denied'))) {
      scopeTypeRef.value = scopeType;
      const isAuth = await hasSettingStatus();
      if (!isAuth) {
        uni.showModal({
          title: '提示',
          content: errMsgMap[scopeType],
          showCancel,
          confirmText: '获取权限',
          success: ({ confirm }) => {
            if (confirm) {
              uni.openSetting();
            }
          },
        });
      }
      return isAuth
    } else if (errMsg?.includes('permission denied') || errMsg?.includes('ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF')) {
      uni.showModal({
        title: '提示',
        content: '请开启手机定位后重新打开程序',
        showCancel: false
      })
      return false
    }

    return true;
  }

  return {
    authErrorCallbak,
  };
}
